package net.zhengxinyun.performance.service.indicators;

import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.data.TownScoreData;
import net.zhengxinyun.performance.dto.HistoryScoreDTO;
import net.zhengxinyun.performance.dto.TownDTO;
import net.zhengxinyun.performance.dto.TownIndexDTO;
import net.zhengxinyun.performance.dto.TownRankDTO;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownScoreEntityMapper;
import net.zhengxinyun.performance.mapper.report.IndexReportMapper;
import net.zhengxinyun.performance.mapper.yearSummaryScore.YearSummaryScoreEntityMapper;
import net.zhengxinyun.performance.service.report.IndexReportService;
import net.zhengxinyun.performance.service.yearSummaryScore.YearSummaryScoreService;

import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.jdbc.Null;
import org.apache.poi.poifs.filesystem.DocumentOutputStream;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Ref;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * Created by hyp1202 on 2018/11/22.
 */
@Service
public class TownScoreServiceImpl implements TownScoreService {

    @Value("${path}")
    public String PATH;

    private TownIndicatorsEntityMapper townIndicatorsEntityMapper;

    private TownMapper townMapper;

    private TownScoreEntityMapper townScoreEntityMapper;

    private DepartmentEntityMapper departmaper;

    private YearSummaryScoreEntityMapper yearSummaryScoreEntityMapper;

    @Autowired
    private TownScoreData townScoreData;

    @Autowired
    private IndexReportMapper indexReportMapper;

    @Autowired
    public TownScoreServiceImpl(TownIndicatorsEntityMapper townIndicatorsEntityMapper,
                                TownMapper townMapper, YearSummaryScoreEntityMapper yearSummaryScoreEntityMapper, TownScoreEntityMapper townScoreEntityMapper, DepartmentEntityMapper departmaper) {
        this.townIndicatorsEntityMapper = townIndicatorsEntityMapper;
        this.townMapper = townMapper;
        this.townScoreEntityMapper = townScoreEntityMapper;
        this.departmaper = departmaper;
        this.yearSummaryScoreEntityMapper = yearSummaryScoreEntityMapper;
    }

    /**
     * --------------------指标查询模块---------------
     *
     * @param townIndicatorsFilter
     * @return
     */
    @Override
    public List<Map<String, Object>> query(TownIndicatorsFilter townIndicatorsFilter, RolePerEntity roleright,UserEntity userEntity) {
        DecimalFormat df = new DecimalFormat("#.00");
        String[] towns = Util.TOWN_HEAD;


        if ("4".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit("");
        }

        /**
         * 所有部门
         */
        List<DepartmentFilter> departlist  = departmaper.query(new DepartmentFilter());
        HashMap<String,String> nameToCode = new HashMap<>();
        HashMap<String,String> codeToName = new HashMap<>();
        for(DepartmentFilter item: departlist)
        {
            nameToCode.put(item.getDepartAddr(),item.getDepartcode());
            codeToName.put(item.getDepartcode(),item.getDepartAddr());
        }

        /*
         * 所有二级指标
         * */
        townIndicatorsFilter.setIndexType("二级指标");
        townIndicatorsFilter.setPageSize(0);

        List<TownIndicatorsFilter> indictorlists = townIndicatorsEntityMapper.query(townIndicatorsFilter);
        List<Map<String,Object>>  scoreMap = new ArrayList<>();
        TownIndicatorsEntity entity;

        //该用户所有不可查看的指标//
        //List<TownIndicatorsFilter> indictorlist = new ArrayList<>();
       // CopyOnWriteArrayList<TownIndicatorsFilter> indictorlist = new CopyOnWriteArrayList<>(indictorlists);
        String indexstr=null;
        if(ObjectUtils.isBlank( roleright ))
        {
            indexstr = userEntity.getIndexRight();
        }else
        {
            indexstr = roleright.getIndexRight();
        }

        List<TownIndicatorsFilter> indictorlist = new ArrayList<>();

        /*
        管理员看全部，不需要二次过滤
         */
        if("admin".equals(userEntity.getUserPermissions())){

            indictorlist = indictorlists;
        }else {
            HashMap<String,Object>  indexsMap = Util.getIndexIdMap(indexstr);
            /**
             * 所有可查看的指标集合
             */
            for(TownIndicatorsFilter item : indictorlists)
            {
                Object ob = indexsMap.get(item.getId().toString());
                String id1 = item.getId().toString();
                if(ObjectUtils.isBlank(ob))
                    continue;
                String id2 = indexsMap.get(id1).toString();
                if(id1.equals(id2))
                {
                    indictorlist.add(item);
                }
            }
        }




        for(TownIndicatorsFilter item : indictorlist)
        {

            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id",          item.getId());
            indexMap.put("indexType", item.getIndexType());
            indexMap.put("leadUnit",  codeToName.get(  item.getLeadUnit() )) ;
            indexMap.put("leadUnitName", item.getLeadUnitName() ) ;
            indexMap.put("indexName", item.getIndexName());
            indexMap.put("responsibilityUnit", item.getResponsibilityUnit());
            indexMap.put("direction", item.getDirection());
            indexMap.put("monthTime", item.getMonthTime());
            indexMap.put("reason", item.getReason());
            indexMap.put("mainUnit", item.getMainUnit());
            townIndicatorsFilter.setIndexId(item.getId()+"");
            if(StringUtils.isBlank(townIndicatorsFilter.getMonthTime()))
            {
                //默认获取上个月时间。
                townIndicatorsFilter.setDateTime(DateUtils.getLastMonth());
            }else {
                townIndicatorsFilter.setDateTime(townIndicatorsFilter.getDateTime().substring(0,4)+townIndicatorsFilter.getMonthTime());

            }

            List<TownIndicatorsFilter> scoreLists =  townScoreEntityMapper.getExportIndexScore(townIndicatorsFilter);

           /* if (StringUtils.isNotBlank(item.getSuperiorIndexId())) {
                entity = townIndicatorsEntityMapper.selectByPrimaryKey(Long.valueOf(item.getSuperiorIndexId()));
                if (entity != null) {
                    indexMap.put("superiorIndexId", entity.getIndexName());
                }
            }*/

            if(ObjectUtils.isNotBlank(scoreLists) )
            indexMap.put("audit", "1");
            else {
                indexMap.put("audit", "0");
            }
            //设置乡镇属性值
            for (TownIndicatorsFilter  scoreItem: scoreLists )
            {

                HashMap<String,Object> values = new HashMap<>();
                values.put("weight", scoreItem.getWeight()); //权重
                values.put("score", Util.formatNumber(2,scoreItem.getScore()) );
                values.put("finalScore",scoreItem.getFinalScore());
                values.put("rank",scoreItem.getRank());



                indexMap.put(codeToName.get(scoreItem.getDepartCode()),values);

                indexMap.put("dateTime",scoreItem.getDateTime());

            }



            /*
                空值设置为 “-”
             */
            for (int i = 0; i < towns.length; i++) {
                if(!indexMap.containsKey(towns[i])){
                    HashMap<String,Object> values = new HashMap<>();
                    values.put("weight","-"); //权重
                    values.put("score", "-" );
                    values.put("finalScore","-");
                    values.put("rank","-");
                    indexMap.put(towns[i],values);
                    indexMap.put("dateTime",townIndicatorsFilter.getDateTime());
                }
            }





            scoreMap.add(indexMap);

        }



        if("1".equals(townIndicatorsFilter.getTableType()))
        {
            /**
             * 遍历合计部分  得分 = 得分率 x 权重 /100
             */
            Map<String,Object> finalScoreHeJi = new HashMap<>();
            finalScoreHeJi.put("indexName","得分合计");
            finalScoreHeJi.put("id",1);

            Map<String,Object> weightHeJi = new HashMap<>();
            weightHeJi.put("indexName","总权值");
            weightHeJi.put("id",2);

            Map<String,Object> scoreHeJi = new HashMap<>();
            scoreHeJi.put("indexName","总得分率");
            scoreHeJi.put("id",3);

            Map<String,Object> rankHeji = new HashMap<>();
            rankHeji.put("indexName","排名");
            rankHeji.put("id",4);


            for (int i = 0; i < towns.length; i++) {
                double finalScoreSum =0;
                double weightSum = 0;
                HashMap<String,Object> finalScoreValue = new HashMap<>();
                HashMap<String,Object> weightValue = new HashMap<>();
                HashMap<String,Object> scoreValue = new HashMap<>();

                for (Map<String, Object> map : scoreMap) {
                    Map<String,Object> townMap = (Map<String, Object>) map.get(towns[i]);
                    Object finalScore = townMap.get("finalScore");
                  //  String rate = score;
                    Object weight = townMap.get("weight");
                   // String weight = /weight1;
                    if(ObjectUtils.isNotBlank(finalScore)&&!"-".equals(finalScore)){
                        finalScoreSum =finalScoreSum+Double.parseDouble(finalScore.toString());
                    }
                    if(ObjectUtils.isNotBlank(weight)&&!"-".equals(weight)){
                        weightSum =weightSum+Double.parseDouble(weight.toString());
                    }

                   // value.put("score",Util.doubleFormat( scoreSum));
                    //value.put("weight",weightSum);
                    finalScoreValue.put("finalScore",Util.doubleFormat( finalScoreSum));
                    //value.put("rank","-");

                    weightValue.put("finalScore",weightSum);
                   // finalv.put("finalScore",Util.doubleFormat( scoreSum));
                  //  rankValue.put("finalScore","-");
                    scoreValue.put("finalScore","-");

                }
               // double  finalScore = scoreSum*weightSum/100;
               // value.put("finalScore",Util.doubleFormat(finalScore));

                finalScoreHeJi.put(towns[i],finalScoreValue);
                weightHeJi.put(towns[i],weightValue);
                if(weightSum!=0){
                    double v = finalScoreSum / weightSum  * 100;
                    scoreValue.put("finalScore",Util.doubleFormat(v));
                }else {
                    scoreValue.put("finalScore",0);
                }


                scoreHeJi.put(towns[i],scoreValue);
               // rankHeji.put(towns[i],rankValue);
            }
            /*
                太难了 还要再次根据得分率计算排名
             */





            List<TownRankDTO> ranDtos  = new ArrayList<>();

            for (String town : towns) {
                TownRankDTO dto  = new TownRankDTO();
                dto.setTownName(town);
               HashMap<String,Object> dtomap= (HashMap<String, Object>) scoreHeJi.get(town);
                dto.setFinalScore(dtomap.get("finalScore")+"");
                ranDtos.add(dto);
            }

            ranDtos= ranDtos.stream().sorted(Comparator.comparingDouble(TownRankDTO::getDoubleRate).reversed()).collect(Collectors.toList());
            //** 计算排名
            int rank =0;
            int no =0;
            double lastScore =-1;
            for (TownRankDTO dto : ranDtos) {
                double fianlScore ;
                if(StringUtils.isBlank(dto.getFinalScore()) || "-".equals(dto.getFinalScore()) )
                {
                    continue;
                }else {
                    fianlScore=Double.parseDouble(dto.getFinalScore());
                }

                if(Double.compare(lastScore,fianlScore)!=0){
                    lastScore = fianlScore;
                    rank=rank+1+no;
                    no=0;
                }else {
                    no++;
                }
                dto.setRank(rank+"");

            }

            for (TownRankDTO dto : ranDtos) {
                    HashMap<String,Object> rankValue = new HashMap<>();
                    rankValue.put("finalScore",dto.getRank());
                    rankHeji.put(dto.getTownName(),rankValue);
            }

            scoreMap.add(finalScoreHeJi);
            scoreMap.add(weightHeJi);
            scoreMap.add(scoreHeJi);
            scoreMap.add(rankHeji);

        }


        return scoreMap;
    }

    /**
     * 获取指标，乡镇，得分这三个值的总页数
     *
     * @param townIndicatorsFilter
     * @return
     */
    public Integer getThreeTableCount(TownIndicatorsFilter townIndicatorsFilter) {
        return townIndicatorsEntityMapper.getThreeTableCount(townIndicatorsFilter);
    }

    /**
     * 设置个乡镇分数
     *
     * @param townIndicatorsFilter
     * @param list
     * @return
     */
    @Override
    @Transactional
    public String setScore(TownIndicatorsFilter townIndicatorsFilter, List<TownIndicatorsFilter> list) {
        TownFilter townFilter = new TownFilter();
        TownScoreEntity townScoreEntity = new TownScoreEntity();
        TownScoreFilter townScoreFilter = new TownScoreFilter();
        for (TownIndicatorsFilter filet : list) {
            if (StringUtils.isBlank(filet.getScore())) {
                return filet.getTownName() + "没有设置分数";
            }
        }
        Collections.sort(list, new Comparator<TownIndicatorsFilter>() {
            @Override
            public int compare(TownIndicatorsFilter o1, TownIndicatorsFilter o2) {
                if (Double.parseDouble(o1.getScore()) < Double.parseDouble(o2.getScore())) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        int rank = 1;
        for (TownIndicatorsFilter filter : list) {
            townFilter.setIndexId(filter.getId().toString());
            townFilter.setTownName(filter.getTownName());
            String id = townMapper.queryId(townFilter).toString();
            townScoreEntity.setIndexId(filter.getId().toString());
            townScoreEntity.setTownId(id);
            townScoreFilter.setIndexId(filter.getId().toString());
            townScoreFilter.setTownId(id);
            townScoreEntity.setMonthTime(filter.getMonthTime());
            townScoreEntity.setRank(rank + "");
            if (StringUtils.isNotBlank(filter.getScore()) && Double.parseDouble(filter.getScore()) <= 100) {
                townScoreEntity.setScore(filter.getScore());
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return filter.getTownName() + "分数输入有误";
            }
            List<TownScoreFilter> filterList = townScoreEntityMapper.query(townScoreFilter);
            //判断数据库是否已有该指标乡镇得分数据，如果有并且审核状态为待审核，则修改该数据
            if (filterList.size() != 0) {
                if ("0".equals(filterList.get(0).getAudit()) || "3".equals(filterList.get(0).getAudit())) {
                    townScoreEntity.setAudit("0");
                    townScoreEntity.setReason("");
                    int t = townScoreEntityMapper.updateByIndexIdAndTownId(townScoreEntity);
                    if (t == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "设置" + filter.getTownName() + "失败请重试";
                    }
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "该指标已审核无法修改";
                }
            } else {
                townScoreEntity.setAudit("1");
                int i = townScoreEntityMapper.insert(townScoreEntity);
                int i1 = setAllScore(townScoreEntity);

                if (i == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "设置" + filter.getTownName() + "失败请重试";
                }
            }
            rank++;
        }
        return "操作成功";
    }

  /*  public int setScore(TownScoreEntity townScoreEntity){
        //查询当前乡镇所有指标的最后分数
        TownScoreFilter scoreFilter = new TownScoreFilter();
        scoreFilter.setTownId(townScoreEntity.getTownId());
        scoreFilter.setVaild("1");
        List<TownScoreFilter> scoreFilters = townScoreEntityMapper.query(scoreFilter);

        Double s = 0.0;
        for (TownScoreFilter score : scoreFilters) {
            String finalScore = score.getFinalScore();
            double d = Double.parseDouble(finalScore);
            s+=d;
        }
    }
*/

    /**
     * 插入指标总分
     *
     * @param townScoreEntity
     * @return
     */
    public int setAllScore(TownScoreEntity townScoreEntity) {
        //查询当前乡镇所有指标的最后分数
        TownScoreFilter scoreFilter = new TownScoreFilter();
        scoreFilter.setTownId(townScoreEntity.getTownId());
        scoreFilter.setVaild("1");
        List<TownScoreFilter> scoreFilters = townScoreEntityMapper.query(scoreFilter);

        Double f = 0.0;//指标总分
//        Double s = 0.0; //得分总分
        for (TownScoreFilter score : scoreFilters) {
            String finalScore = score.getFinalScore();
            if(StringUtils.isBlank(finalScore))
                continue;
            double f1 = Double.parseDouble(finalScore);
            /*String scoreScore = score.getScore();
            double s1 = Double.parseDouble(scoreScore);*/

            f += f1;

//            s += s1;

        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        String year = sdf.format(date);


        YearSummaryScoreEntity scoreEntity = new YearSummaryScoreEntity();
        YearSummaryScoreFilter yearSummaryScoreFilter = new YearSummaryScoreFilter();
        yearSummaryScoreFilter.setDeptCode(townScoreEntity.getTownId());
        yearSummaryScoreFilter.setYear(year);
        List<YearSummaryScoreFilter> query = yearSummaryScoreEntityMapper.query(yearSummaryScoreFilter);

        //设置总分
        DecimalFormat df = new DecimalFormat("#.00");
       /* String str = df.format(s);
        scoreEntity.setScore(str);*/

        //设置指标总分
        String strf = df.format(f);

        scoreEntity.setIndustryScore(strf);

        scoreEntity.setYear(year);
        scoreEntity.setDeptCode(townScoreEntity.getTownId());
        if (query.size() > 0) {
            for (YearSummaryScoreFilter filter : query) {
                scoreEntity.setId(filter.getId());

                return yearSummaryScoreEntityMapper.updateByPrimaryKeySelective(scoreEntity);
            }
        } else {
            return yearSummaryScoreEntityMapper.insertSelective(scoreEntity);
        }
        return 2;

    }

    /**
     * 添加总分方法2
     *
     * @param townScoreEntity
     * @return
     */
    public int setAllScore1(TownScoreEntity townScoreEntity) {
        //查询当前乡镇所有分数
        TownScoreFilter scoreFilter = new TownScoreFilter();
        scoreFilter.setTownId(townScoreEntity.getTownId());
        scoreFilter.setVaild("1");
        List<TownScoreFilter> scoreFilters = townScoreEntityMapper.query(scoreFilter);
        //计算所有分数总和
        int scoreSum = 0;
        int weightSum = 0;
        for (TownScoreFilter filter : scoreFilters) {
            if (filter.getScore() != null) {
                int score = Integer.parseInt(filter.getScore());
                scoreSum += score;
            }
            if (filter.getWeight() != null) {
                int weight = Integer.parseInt(filter.getWeight());
                weightSum += weight;
            }
        }
        //计算结果
        String format = "";
        if (weightSum != 0) {
            double d = (double) weightSum / 100;
            double s = (double) scoreSum / d;
            DecimalFormat df = new DecimalFormat("#.00");
            format = df.format(s);

        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        String year = sdf.format(date);

        YearSummaryScoreEntity scoreEntity = new YearSummaryScoreEntity();
        YearSummaryScoreFilter yearSummaryScoreFilter = new YearSummaryScoreFilter();
        yearSummaryScoreFilter.setDeptCode(townScoreEntity.getTownId());
        yearSummaryScoreFilter.setYear(year);
        List<YearSummaryScoreFilter> query = yearSummaryScoreEntityMapper.query(yearSummaryScoreFilter);
        scoreEntity.setScore(format);

        scoreEntity.setYear(year);
        scoreEntity.setDeptCode(townScoreEntity.getTownId());

        if (query.size() > 0) {
            for (YearSummaryScoreFilter filter : query) {
                scoreEntity.setId(filter.getId());
                return yearSummaryScoreEntityMapper.updateByPrimaryKeySelective(scoreEntity);
            }
        } else {
            return yearSummaryScoreEntityMapper.insertSelective(scoreEntity);
        }

        return 2;

    }

    /**
     * 管理员批量通过，通过townFilter集合传对应的乡镇id和月份确定是审核的哪些乡镇，在根据sql语句直接修改
     *
     * @param list
     * @return
     */
    @Override
    @Transactional
    public String auditAllPass(List<TownIndicatorsFilter> list) {
        for (TownIndicatorsFilter townIndicatorsFilter : list) {
            List<TownFilter> townList = townMapper.queryByIndexId(townIndicatorsFilter.getId().toString());
            TownScoreEntity townScoreEntity = new TownScoreEntity();
            TownScoreFilter filter = new TownScoreFilter();
            for (TownFilter townFilter : townList) {
                townScoreEntity.setTownId(townFilter.getId().toString());
                townScoreEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
                filter.setTownId(townFilter.getId().toString());
                filter.setMonthTime(townIndicatorsFilter.getMonthTime());
                List<TownScoreFilter> filterList = townScoreEntityMapper.query(filter);
                if (CollectionUtils.isEmpty(filterList)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "数据有误，请联系管理员";
                }
                if (!"1".equals(filterList.get(0).getAudit())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "未到管理员审核阶段，请重新审核";
                }
                townScoreEntity.setAudit("2");
                townScoreEntity.setFinalScore(Util.getFinalScore(filterList.get(0).getScore(), townFilter.getWeight()));
                int i = townScoreEntityMapper.updateAuditForTownId(townScoreEntity);
                if (i == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "审核通过失败";
                }
            }
        }
        return "操作成功";
    }

    @Override
    @Transactional
    public String responsibleAllPass(List<TownIndicatorsFilter> list) {
        for (TownIndicatorsFilter townIndicatorsFilter : list) {
            List<TownFilter> townList = townMapper.queryByIndexId(townIndicatorsFilter.getId().toString());
            TownScoreEntity townScoreEntity = new TownScoreEntity();
            TownScoreFilter filter = new TownScoreFilter();
            for (TownFilter townFilter : townList) {
                townScoreEntity.setTownId(townFilter.getId().toString());
                townScoreEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
                filter.setTownId(townFilter.getId().toString());
                filter.setMonthTime(townIndicatorsFilter.getMonthTime());
                List<TownScoreFilter> filterList = townScoreEntityMapper.query(filter);
                if (CollectionUtils.isEmpty(filterList)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "数据有误，请联系管理员";
                }
                if (!"0".equals(filterList.get(0).getAudit())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "未到责任人审核阶段，请重新审核";
                }
                townScoreEntity.setAudit("1");
                int i = townScoreEntityMapper.updateAuditForTownId(townScoreEntity);
                if (i == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "审核通过失败";
                }
            }
        }
        return "操作成功";
    }

    @Override
    @Transactional
    public String noPass(TownIndicatorsFilter townIndicatorsFilter) {
        if (StringUtils.isBlank(townIndicatorsFilter.getReason())) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "回退原因不能为空";
        }
        TownScoreEntity townScoreEntity = new TownScoreEntity();
        TownScoreFilter townScoreFilter = new TownScoreFilter();
        townScoreFilter.setIndexId(townIndicatorsFilter.getId().toString());
        townScoreFilter.setMonthTime(townIndicatorsFilter.getMonthTime());
        List<TownScoreFilter> list = townScoreEntityMapper.query(townScoreFilter);
        for (TownScoreFilter filter : list) {
            townScoreEntity.setAudit("3");
            townScoreEntity.setReason(townIndicatorsFilter.getReason());
            townScoreEntity.setTownId(filter.getTownId());
            townScoreEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
            int i = townScoreEntityMapper.updateAuditForTownId(townScoreEntity);
            if (i == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "审核通过失败";
            }
        }
        return "操作成功";
    }

    @Override
    public List<Map<String, Object>> queryForAudit(TownIndicatorsFilter townIndicatorsFilter) {
        if ("4".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(townIndicatorsFilter.getAudit())) {
            townIndicatorsFilter.setAudit("");
        }
      List<TownIndicatorsFilter> list = townIndicatorsEntityMapper.queryScoreForAudit(townIndicatorsFilter);
        List<Map<String, Object>> indexList = new ArrayList<>();

        /*List<DepartmentFilter> departlist = departmaper.query(new DepartmentFilter());
        HashMap<String, String> codetonamemap = new HashMap<>();
        for (DepartmentFilter item : departlist) {
            codetonamemap.put(item.getDepartcode(), item.getDepartAddr());
        }*/

        //所有单位部门。
        List<DepartmentFilter> departlist  = departmaper.query(new DepartmentFilter());
        HashMap<String,String> nameToCode = new HashMap<>();
        HashMap<String,String> codeToName = new HashMap<>();
        for(DepartmentFilter item: departlist)
        {
            nameToCode.put(item.getDepartAddr(),item.getDepartcode());
            codeToName.put(item.getDepartcode(),item.getDepartAddr());
        }
        /*
        * 所有二级指标
        * */

        List<TownIndicatorsFilter> indictorlist = townIndicatorsEntityMapper.query(townIndicatorsFilter);
        List<Map<String,Object>>  scoreMap = new ArrayList<>();
        TownIndicatorsEntity entity;
        for(TownIndicatorsFilter item : indictorlist)
        {
            townIndicatorsFilter.setDateTime(DateUtils.getCurrentMonth());


            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id", item.getId());
            indexMap.put("indexType", item.getIndexType());
            indexMap.put("leadUnit", item.getLeadUnit());
            indexMap.put("indexName", item.getIndexName());
            indexMap.put("responsibilityUnit", item.getResponsibilityUnit());
            indexMap.put("direction", item.getDirection());
            indexMap.put("audit", item.getAudit());
            indexMap.put("monthTime", item.getMonthTime());
            indexMap.put("reason", item.getReason());
            indexMap.put("mainUnit", item.getMainUnit());
            townIndicatorsFilter.setIndexId(item.getId()+"");
            List<TownIndicatorsFilter> scoreLists =  townScoreEntityMapper.getExportIndexScore(townIndicatorsFilter);
            //乡镇数据为空，加载乡镇属性值。
          /*  if(ObjectUtils.isBlank(scoreLists))
            {
                for(String head:heads)
                {
                    indexMap.put(head,null);
                    indexMap.put("dateTime",null);
                }
            }*/

            if (StringUtils.isNotBlank(item.getSuperiorIndexId())) {
                entity = townIndicatorsEntityMapper.selectByPrimaryKey(Long.valueOf(item.getSuperiorIndexId()));
                if (entity != null) {
                    indexMap.put("superiorIndexId", entity.getIndexName());
                }
            }


            //设置乡镇属性值
            for (TownIndicatorsFilter  scoreItem: scoreLists )
            {
                indexMap.put(codeToName.get(scoreItem.getDepartCode()), StringUtils.isBlank(scoreItem.getScore())?null:Double.parseDouble(scoreItem.getScore())  );
                indexMap.put("dateTime",scoreItem.getDateTime());
            }


            scoreMap.add(indexMap);

        }



         /*
        for (TownIndicatorsFilter filter : list) {
            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id", filter.getId());
            indexMap.put("indexType", filter.getIndexType());
            indexMap.put("leadUnit", filter.getLeadUnit());
            indexMap.put("indexName", filter.getIndexName());
            indexMap.put("responsibilityUnit", filter.getResponsibilityUnit());
            indexMap.put("direction", filter.getDirection());
            indexMap.put("audit", filter.getAudit());
            indexMap.put("monthTime", filter.getMonthTime());
            indexMap.put("reason", filter.getReason());
            indexMap.put("mainUnit", filter.getMainUnit());
            if (StringUtils.isNotBlank(filter.getWeight())) {
                indexMap.put("weight", Double.parseDouble(filter.getWeight()));
            } else {
                indexMap.put("weight", null);
            }
            indexMap.put("dateTime", filter.getDateTime());
            //把对应的上级指标名返回给前端
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                entity = townIndicatorsEntityMapper.selectByPrimaryKey(Long.valueOf(filter.getSuperiorIndexId()));
                if (entity != null) {
                    indexMap.put("superiorIndexId", entity.getIndexName());
                }
            }
            List<TownFilter> townList = townMapper.queryTownAndScore(filter.getId().toString());
            Map<String, Object> townMap = new HashMap<>();
            for (TownFilter townFilter : townList) {
                if ("0".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(codetonamemap.get(townFilter.getTownName()), Util.doubleParse(townFilter.getWeight()));

                    // indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getWeight()));
                } else if ("1".equals(townIndicatorsFilter.getScoreType())) {
                    // indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getScore()));
                    indexMap.put(codetonamemap.get(townFilter.getTownName()), Util.doubleParse(townFilter.getScore()));
                } else if ("2".equals(townIndicatorsFilter.getScoreType())) {

                    indexMap.put(codetonamemap.get(townFilter.getTownName()), Util.doubleParse(townFilter.getFinalScore()));
                    // indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getFinalScore()));
                } else if ("3".equals(townIndicatorsFilter.getScoreType())) {
                    indexMap.put(codetonamemap.get(townFilter.getTownName()), Util.doubleParse(townFilter.getRank()));
                    //indexMap.put(townFilter.getTownName(), Util.doubleParse(townFilter.getRank()));
                } else if ("4".equals(townIndicatorsFilter.getScoreType())) {
                    Map<String, Object> map = new HashMap<>();
                    if (StringUtils.isNotBlank(townFilter.getWeight())) {
                        map.put("weight", Util.doubleParse(townFilter.getWeight()));
                    } else {
                        map.put("weight", null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getScore())) {
                        map.put("score", Util.doubleParse(townFilter.getScore()));
                    } else {
                        map.put("score", null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getFinalScore())) {
                        map.put("finalScore", Util.doubleParse(townFilter.getFinalScore()));
                    } else {
                        map.put("finalScore", null);
                    }
                    if (StringUtils.isNotBlank(townFilter.getRank())) {
                        map.put("rank", Util.doubleParse(townFilter.getRank()));
                    } else {
                        map.put("rank", null);
                    }
                    townMap.put(townFilter.getTownName(), map);
                }
            }
            if (townMap.size() != 0) {
                indexMap.put("townList", townMap);
            }
            indexList.add(indexMap);
        }*/
        return scoreMap;
    }

    public int getAuditCount(TownIndicatorsFilter townIndicatorsFilter) {
        return townIndicatorsEntityMapper.getAuditCount(townIndicatorsFilter);
    }

    @Override
    @Transactional
    public String setFirstFinalScore(TownIndicatorsFilter townIndicatorsFilter) {
        TownIndicatorsEntity indicatorsEntity = townIndicatorsEntityMapper.selectByPrimaryKey(townIndicatorsFilter.getId());
        indicatorsEntity.setMonthTime(townIndicatorsFilter.getMonthTime());
        if (townIndicatorsEntityMapper.queryNullFinal(indicatorsEntity) == 0) {
            Double finalScore = townIndicatorsEntityMapper.queryFirstFinalScore(indicatorsEntity);
            TownScoreEntity entity = new TownScoreEntity();
            entity.setIndexId(indicatorsEntity.getSuperiorIndexId());
            entity.setMonthTime(townIndicatorsFilter.getMonthTime());
            entity.setDateTime(indicatorsEntity.getDateTime());
            entity.setFinalScore(finalScore.toString());
            entity.setAudit("2");
            int i = townScoreEntityMapper.insert(entity);
            if (i == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "一级指标得分设置失败";
            }
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "还没够";
        }
        return "操作成功";
    }

    @Override
    @Transactional
    public String importTownScore(MultipartFile file) {
        if (file.getOriginalFilename().endsWith(".xls") && file.getOriginalFilename().endsWith(".xlsx")) {
            return "文件后缀不对";
        }
        String filePath;
        try {
            Util.write(file.getOriginalFilename(), file.getInputStream());
            filePath = this.PATH + file.getOriginalFilename();
            filePath = new String(filePath.getBytes("utf-8"), "utf-8");
            if (com.sirdc.modules.utils.StringUtils.isBlank(filePath)) {
                return "filePath为空";
            }

            DecimalFormat df = new DecimalFormat("#.00");
            List<List<TownScoreEntity>> lists = townScoreData.importTownScore(filePath);
            for (List<TownScoreEntity> list : lists) {
                for (TownScoreEntity entity : list) {
                    if(StringUtils.isNotBlank(entity.getScore())){
                        Double db = Double.parseDouble(entity.getScore());
                        entity.setScore( df.format(db));
                    }

                    int i = townScoreEntityMapper.insert(entity);
                    if (i == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "导入失败！";
                    }
                }
            }
            return "导入成功";
        } catch (Exception e) {
            return "导入失败!";
        }
    }

    @Override
    public String importScore(List<TownEntity> lists, Long id,UserEntity user,String datetime) {
        //所有部门;
        List<DepartmentFilter> departlist = departmaper.query(new DepartmentFilter());
        HashMap<String, String> nameToCode = new HashMap<>();
        for (DepartmentFilter item : departlist) {
            nameToCode.put(item.getDepartAddr(), item.getDepartcode());
        }

        TownIndicatorsFilter fil = new TownIndicatorsFilter();
        fil.setId(id);
//         List<TownIndicatorsFilter> list = townIndicatorsEntityMapper.queryScoreByIndexId(fil);
        TownScoreFilter scoreFilter = new TownScoreFilter();
        scoreFilter.setIndexId(id.toString());
        scoreFilter.setDateTime(datetime);

        /**
         * 导入前先查出来判断是否存在数据
         */
        List<TownScoreFilter> listscore = townScoreEntityMapper.query(scoreFilter);
        if (ObjectUtils.isNotBlank(listscore)) {
            for (TownScoreFilter item : listscore) {
                TownScoreEntity entity = new TownScoreEntity();
                entity.setVaild("0");//设置为无效
                entity.setId(Long.parseLong(item.getId()));
                int updatacode = townScoreEntityMapper.updateByPrimaryKeySelective(entity);
                System.out.println(updatacode + "=========================================");
                if (updatacode == 0) {
                    System.out.println("更新失败");
                }
            }
        }
/*
               指标指标权重；
         */
        List<TownFilter> townWeight = townMapper.queryByIndexId(id.toString());
        HashMap<String,String> weghtMap = new HashMap<>();
        for(TownFilter filter : townWeight)
        {
            weghtMap.put(filter.getDepartcode()+"",filter.getWeight());
        }

            /*
                计算得分 排名 得分 = 权重x得分率/100
             */

            int rank =0;
            int no = 0;
            double lastScore =-1;
        for(TownEntity item: lists)
        {
            TownEntity town = item;



            TownScoreEntity  score = new TownScoreEntity();

            if(StringUtils.isBlank(item.getScore()))
                continue;
            String townId =nameToCode.get(item.getTownName());
            String weightstr = weghtMap.get(townId );
            if(StringUtils.isBlank(weightstr))
                continue;
            if( Double.compare(lastScore,town.getSocreRate())!=0)
            {
                lastScore=town.getSocreRate();
                rank =rank+1+no;

                no =0;
            }else {
                no++;
            }
            score.setRank(rank+"");
            double weight= Double.parseDouble(weightstr);
            double finlescore = item.getSocreRate()*weight/100;
            String scoreStr= NumberUtils.keepPrecision(finlescore,2);
            score.setScore(item.getScore());
            score.setTownId(townId);
            score.setFinalScore(scoreStr);
            score.setIndexId(id+"");
            score.setAudit(1+"");
            score.setVaild(1+"");

            score.setDateTime(datetime);//
            score.setIndexWriter(user.getId());
            score.setIndexDate(DateUtils.getCurrentDateTime());
            townScoreEntityMapper.insert(score);


        }


        /**
         * 保存到汇报记录表
         */

/*
        IndexReportFilter reportfiter  = new IndexReportFilter();
        reportfiter.setIndexClass(2);
        reportfiter.setIndexDate(DateUtils.getCurrentMonth());
        reportfiter.setIndexId(id);
        List<IndexReportFilter> indexReportFilters = indexReportMapper.query(reportfiter);
        if(ObjectUtils.isNotBlank(indexReportFilters))
        {
            for(IndexReportFilter item:indexReportFilters)
            {
                indexReportMapper.deleteReport(item.getId());
            }
        }


        IndexReport  report = new IndexReport();
        report.setIndexClass(2);
        report.setIndexWriter(user.getId().toString());
        report.setIndexDate(DateUtils.getCurrentMonth());
        report.setIndexTime(DateUtils.getCurrentTime());
        report.setIndexId(id);
        report.setIndexStatue("1");
        indexReportMapper.saveReport(report);*/


        return null;
    }

    /**导出后分数查询
     *
     * @param indexId
     * @return
     */
    @Override
    public HashMap<String, Object> queryAfterImport(String indexId,String datetime) {

        String[] head = Util.TOWN_HEAD;

        //所有部门;
        HashMap<String, String> codetonamemap = getAllDepartmen();
        HashMap<String, Object> resultmap = new HashMap<>();
       // String datetime =DateUtils.getCurrentMonth();
        List<TownScoreFilter> list = townScoreEntityMapper.queryAfterImport(indexId,null,datetime);
        if (ObjectUtils.isNotBlank(list))
        {
            //分装前端需要的数据 按照乡镇分类
           // String datetime = ObjectUtils.isNotBlank(list)?list.get(0).getDateTime():"";
            HashMap<String, Object> weightMap = new HashMap<>(); //权重
            weightMap.put("names", "权重");
            weightMap.put("month", datetime);
            // listWeight.add(weightMap);
            HashMap<String, Object> rateMap = new HashMap<>(); //得分率
            rateMap.put("names", "得分率");
            rateMap.put("month", datetime);
            //  listrate.add(rateMap);
            HashMap<String, Object> scoreMap = new HashMap<>();
            scoreMap.put("names", "得分");
            scoreMap.put("month", datetime);
            // listScore.add(scoreMap);
            HashMap<String, Object> rankMap = new HashMap<>();
            rankMap.put("names", "排名");
            rankMap.put("month", datetime);
            // listRank.add(rankMap);
            DecimalFormat df = new DecimalFormat("#.00");
            for (String townName : head) {
                for (TownScoreFilter item : list) {

                    if (townName.equals(codetonamemap.get(item.getTownId()))) {

                        // weightMap = new HashMap<>(); //权重
                        weightMap.put(townName, item.getWeight());
                        // listWeight.add(weightMap);
                        if(StringUtils.isNotBlank(item.getScore())){
                            Double db  = Double.parseDouble(item.getScore());
                            item.setScore(df.format(db));
                        }
                        // rateMap = new HashMap<>(); //得分率
                        rateMap.put(townName, item.getScore());
                        // listrate.add(rateMap);

                        // scoreMap = new HashMap<>();
                        if(StringUtils.isNotBlank(item.getFinalScore())){
                            Double db  = Double.parseDouble(item.getFinalScore());
                            item.setFinalScore(df.format(db));
                        }
                        scoreMap.put(townName, item.getFinalScore());
                        //listScore.add(scoreMap);

                        // rankMap = new HashMap<>();
                        rankMap.put(townName, item.getRank());
                        //listRank.add(rankMap);


                    }
                }


            }

            resultmap.put("rank", rankMap);
            resultmap.put("score", scoreMap);
            resultmap.put("rate", rateMap);
            resultmap.put("weight", weightMap);

        }






        return resultmap;
    }

    /**
     * 指标分析
     * @param indexId
     * @param townId
     * @param request
     * @return
     */
    @Override
    public HashMap<String,Object>  queryTownIndexValue(String indexId, String townId, HttpServletRequest request) {
        HashMap<String,Object> map = new HashMap<>();
        String year = (String) request.getSession().getAttribute("currentYear");
        if(StringUtils.isBlank(year))
        {
             new Thread("登录过期，请刷新页面");
             map.put("code",500);
        }else
            map.put("code",200);

        String datetime = DateUtils.getCurrentMonth();
        TreeMap<String,String> datemap = Util.yearmonth(year);//当年所有月份


        List<TownScoreFilter> list =townScoreEntityMapper.queryAfterImport(indexId,townId,null);
        List<String> names = new ArrayList<>();
        List<String> score = new ArrayList<>();
        List<String> rank = new ArrayList<>();
        List<String> weight = new ArrayList<>();
        HashMap<String,TownScoreFilter>  valueMap = new HashMap<>();

        List<HashMap<String,Object>> listMap = new ArrayList<>();
        HashMap<String,Object> gridMap = new HashMap<>();
        for (TownScoreFilter scoreFilter: list)
        {
            valueMap.put(scoreFilter.getDateTime(),scoreFilter);


            HashMap<String,Object> proValue = new HashMap<>();

            proValue.put("score",scoreFilter.getScore());
            proValue.put("finalScore",scoreFilter.getFinalScore());
            proValue.put("rank",scoreFilter.getRank());
            proValue.put("weight",scoreFilter.getWeight());
            gridMap.put("month"+scoreFilter.getDateTime().substring(4,6),proValue);

        }
        listMap.add(gridMap);

        for(Map.Entry<String,String> iter : datemap.entrySet() )
        {
            //HashMap<String,Object> gridMap = new HashMap<>();//表格数据map

          if(valueMap.containsKey(iter.getKey()))
          {
              TownScoreFilter townscore = valueMap.get(iter.getKey());
              names.add(townscore.getDateTime());
              score.add(townscore.getScore());
              rank.add(townscore.getFinalScore());
              weight.add(townscore.getWeight());
             /* gridMap.put("score",townscore.getScore());
              gridMap.put("finalScore",townscore.getFinalScore());
              gridMap.put("rank",townscore.getRank());
              gridMap.put("weight",townscore.getWeight());
              listMap.add(gridMap);*/

          }else {
              names.add(iter.getValue().toString());
              score.add("0");
              rank.add("0");
              weight.add("0");

             /* gridMap.put("score",null);
              gridMap.put("finalScore",null);
              gridMap.put("rank",null);
              gridMap.put("weight",null);
              listMap.add(gridMap);*/


          }


        }



        map.put("name",names);
        map.put("score",score);
        map.put("finalScore",rank);
        map.put("weight",weight);
        map.put("gridList",listMap);

        return map ;
    }


    /**
     * 20190625 xxq
     * 查询分数，权重 ，指标。
     *
     * @param filter
     * @return
     */
    @Override
    public List<TownIndicatorsFilter> getIndictScore(TownIndicatorsFilter filter) {
        return townScoreEntityMapper.getIndexScore(filter);
    }


    @Override
    public List<TownIndicatorsFilter> getExporScore(TownIndicatorsFilter filter) {
        return townScoreEntityMapper.getExportIndexScore(filter);
    }


    /**
     * 指标分析数据处理
     * @param datetime
     * @return
     */
    @Override
    public  List<Map<String,Object>> queryIndexRank(String datetime) {
        String[] heads ={"塘前乡","葛岭镇","樟城镇","城峰镇","清凉镇",
                "富泉乡","岭路乡","赤锡乡","梧桐镇","嵩口镇","洑口乡",
                "盖洋乡","长庆镇","东洋乡","霞拔乡","同安镇","大洋镇",
                "盘谷乡","红星乡","白云乡","丹云乡"};

        List<DepartmentFilter> departlist  = departmaper.query(new DepartmentFilter());
        HashMap<String,String> nameToCode = new HashMap<>();
        HashMap<String,String> codeToName = new HashMap<>();
        for(DepartmentFilter item: departlist)
        {
            nameToCode.put(item.getDepartAddr(),item.getDepartcode());
            codeToName.put(item.getDepartcode(),item.getDepartAddr());
        }

        TownIndicatorsFilter filter = new TownIndicatorsFilter();
        filter.setIndexType("二级指标");
        String year = datetime.substring(0, 4);
        System.out.println("======================="+year+"=========================");
        // filter.setDateTime(year);
        //所有二级指标
        filter.setDateTime(year);
        List<TownIndicatorsFilter> indictorlist = townIndicatorsEntityMapper.query(filter);


        List<Map<String,Object>>  scoreMap = new ArrayList<>();
        for(TownIndicatorsFilter item : indictorlist)
        {
            filter.setDateTime(datetime);


            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id", item.getId());
            indexMap.put("indexType", item.getIndexType());
            indexMap.put("leadUnit", item.getLeadUnit());
            indexMap.put("indexName", item.getIndexName());
            indexMap.put("responsibilityUnit", item.getResponsibilityUnit());
            indexMap.put("direction", item.getDirection());
            indexMap.put("audit", item.getAudit());
            indexMap.put("monthTime", item.getMonthTime());
            indexMap.put("reason", item.getReason());
            indexMap.put("mainUnit", item.getMainUnit());
            filter.setIndexId(item.getId()+"");
            List<TownIndicatorsFilter> scoreLists =  townScoreEntityMapper.getExportIndexScore(filter);
           //乡镇数据为空，加载乡镇属性值。
            if(ObjectUtils.isBlank(scoreLists))
            {
                for(String head:heads)
                {
                    indexMap.put(head,null);
                    indexMap.put("dateTime",null);
                }
            }
            //设置乡镇属性值
            for (TownIndicatorsFilter  scoreItem: scoreLists )
            {
                indexMap.put(codeToName.get(scoreItem.getDepartCode()), StringUtils.isBlank(scoreItem.getScore())?null:Double.parseDouble(scoreItem.getScore())  );
                indexMap.put("dateTime",scoreItem.getDateTime());
            }


            scoreMap.add(indexMap);

        }

        return scoreMap;
    }

    @Override
    public String update(TownScoreEntity townScoreEntity) {
        return null;
    }

    @Override
    public String insert(TownScoreEntity townScoreEntity) {
        return null;
    }

    @Override
    public String delete(TownScoreEntity townScoreEntity) {
        return null;
    }


    //所有部门
    @Override
    public  HashMap<String, String> getAllDepartmen()
    {
        //所有部门;
        List<DepartmentFilter> departlist = departmaper.query(new DepartmentFilter());
        HashMap<String, String> codetonamemap = new HashMap<>();
        for (DepartmentFilter item : departlist) {
            codetonamemap.put(item.getDepartcode(), item.getDepartAddr());
        }
        return codetonamemap;
    }

    /**
     * 指标分析中，单个指标的分析
     */
    @Override
    public Map indexAnalyse(Long indexId, String dateTime) {

        TownFilter townFilter = new TownFilter();
        townFilter.setIndexId(indexId.toString());
        townFilter.setDatetime(dateTime.substring(0,4));

        List<TownEntity> townFilters = townMapper.selectWeight(townFilter);
        int m=0,n=0;
        String inTown="",outTown="";
        for(TownEntity tw:townFilters)
        {
            if(StringUtils.isNotBlank(tw.getWeight()))
            {
                //参加考核的乡镇：
                m++;
            }else {
                n++;
                outTown=outTown+tw.getTownName()+",";

            }
        }
        String msg = "该指标考核的乡镇"+m+"个,不参与考核的乡镇"+n+"个";
        if(n>0)
            msg=msg+",分别为："+outTown;

        List<TownScoreFilter> list = townScoreEntityMapper.queryAfterImport(indexId.toString(),null,dateTime);
        List< Map<String,Object> > topList = new ArrayList<>();
        List< Map<String,Object> > behindList = new ArrayList<>();
        list = list.stream().sorted(  (o1, o2) -> StringUtils.toInteger(o1.getRank()) -StringUtils.toInteger(o2.getRank())   ).collect(Collectors.toList());


        for(TownScoreFilter town: list )
        {
            if(StringUtils.isBlank(town.getRank()))
                continue;

            int rank  =Integer.parseInt( town.getRank())  ;
            if(rank<=10){
                Map<String,Object> topRank = new HashMap<>();
                topRank.put("townName",town.getTownName());
                topRank.put("townRank",town.getRank());
                topList.add(topRank);

            }
            if(rank>15)
            {
                Map<String,Object> behindRank = new HashMap<>();
                behindRank.put("townName",town.getTownName());
                behindRank.put("townRank",town.getRank());
                behindList.add(behindRank);
            }


        }
        Map<String,Object> map = new HashMap<>();
        map.put("indexInfo",msg);
        map.put("topRank",topList);
        map.put("behindRank",behindList);
        return  map;








    }

    /*
        乡镇分析
     */

    @Override
    public HashMap<String, Object> townAnalyse(String townid, String datetime,Long  indexId,int top,int bad) {
        TownFilter townFilter = new TownFilter();
        townFilter.setDepartcode(townid);
        townFilter.setDatetime(datetime.substring(0,4));

          /*  该乡镇下所有考核的指标的权重*/
        List<TownEntity> townFilters = townMapper.selectWeight(townFilter);
        //权重指标总数
        Integer sumweight = townFilters.stream().map(TownEntity::weightInt).reduce(0, Integer::sum);
        int weightNum  = townFilters.stream().
                filter(entity -> StringUtils.isNotBlank(entity.getWeight()))
                .collect(Collectors.toList()).size();
        String str  = "该乡镇考核"+weightNum+"个指标,权重值 "+sumweight+"。";
        TownScoreFilter tsf = new TownScoreFilter();
        tsf.setDateTime(datetime);
        tsf.setTownId(townid);
        tsf.setCurrentYear(datetime.substring(0,4));
        List<TownIndexDTO> list  = townScoreEntityMapper.selectIndexScore(tsf);

        List<Map<String,Object>> goodList = new ArrayList<>();
        List<Map<String,Object>> badList = new ArrayList<>();
        /**
         * 完成较好的有几个 和完成较差的
         */
        for(TownIndexDTO dto :list )
        {
            if(dto.getRankIntValue()<=top&&dto.getRankIntValue()!=0)
            {
                Map<String,Object> dtomap = new HashMap<>();
                dtomap.put("indexName",dto.getIndexName());
                dtomap.put("indexRank",dto.getRank());

                goodList.add(dtomap);
            }
            if(dto.getRankIntValue()>=bad)
            {
                Map<String,Object> dtomap = new HashMap<>();
                dtomap.put("indexName",dto.getIndexName());
                dtomap.put("indexRank",dto.getRank());
                badList.add(dtomap);
            }

            if(StringUtils.isBlank(dto.getRank()))
            {
                dto.setRank("");
            }
            if(StringUtils.isBlank(dto.getFinalScore()))
            {
                dto.setFinalScore("");
            }
            if(StringUtils.isBlank(dto.getMaxScore()))
            {
                dto.setMaxScore("");
            }
            if(StringUtils.isBlank(dto.getMinScore()   ))
            {
                dto.setMinScore("");
            }
            if(StringUtils.isBlank(dto.getScore()))
            {
                dto.setScore("");
            }else {
                dto.setScore(NumberUtils.keepPrecision(StringUtils.toDouble(dto.getScore()),2 ));
            }
            if(StringUtils.isBlank(dto.getWeight()))
            {
                dto.setWeight("");
            }

        }

        /**
         * 指标报告
         */
        HashMap<String,Object> result = new HashMap<>();
        result.put("goodIndex",goodList);
        result.put("goodSize",goodList.size());
        result.put("badIndex",badList);
        result.put("badSize",badList.size());
        result.put("analy",list);
        result.put("mainword",str);


        return result;
    }

    /**
     * 历史数据
     * @param indexId
     * @return
     */
    @Override
    public List<HistoryScoreDTO> TownHistoryData(Long indexId) {

        DepartmentFilter departmentFilter = new DepartmentFilter();
        departmentFilter.setDepartType("乡镇");
        List<DepartmentFilter> deptlists = departmaper.query(departmentFilter);
        List<HistoryScoreDTO> historys = new ArrayList<>();
        for (DepartmentFilter item : deptlists) {

            List<TownScoreFilter> list = townScoreEntityMapper.queryAfterImport(indexId+"",item.getDepartcode(),null);
            HistoryScoreDTO dto = new HistoryScoreDTO();
            for (TownScoreFilter score : list) {

                String dateTime = score.getDateTime();
                dateTime = dateTime.substring(dateTime.length()-2,dateTime.length());
                System.out.println(dateTime);
                dto.setDeptName(item.getDepartAddr());
                switch (dateTime){

                    case "01":
                        dto.setMonth1(score.getFinalScore());
                    break;

                    case "02":
                        dto.setMonth2(score.getFinalScore());
                        break;
                    case "03":
                        dto.setMonth3(score.getFinalScore());
                        break;
                    case "04":
                        dto.setMonth4(score.getFinalScore());
                        break;
                    case "05":
                        dto.setMonth5(score.getFinalScore());
                        break;
                    case "06":
                        dto.setMonth6(score.getFinalScore());
                        break;
                    case "07":
                        dto.setMonth7(score.getFinalScore());
                        break;
                    case "08":
                        dto.setMonth8(score.getFinalScore());
                        break;
                    case "09":
                        dto.setMonth9(score.getFinalScore());
                        break;
                    case "10":
                        dto.setMonth10(score.getFinalScore());
                        break;
                    case "11":
                        dto.setMonth11(score.getFinalScore());
                        break;
                    case "12":
                        dto.setMonth12(score.getFinalScore());
                        break;



                }


            }

            historys.add(dto);

        }
        //System.out.println(historys);

      //  List<TownScoreFilter> list = townScoreEntityMapper.queryAfterImport(indexId+"",null,null);

        return historys;
    }
}
